package tools;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Formatter;

public class Format {

	public static String encodeURL(String hexString) throws Exception {
		if(hexString==null || hexString.isEmpty()){
			return "";
		}
		if(hexString.length()%2 != 0){
			throw new Exception("String is not hex, length NOT divisible by 2: "+hexString);
		}
		int len = hexString.length();
		char[] output = new char[len+len/2];
		int i=0;
		int j=0;
		while(i<len){
			output[j++]='%';
			output[j++]=hexString.charAt(i++);
			output[j++]=hexString.charAt(i++);
		}
		return new String(output);
	}



	public static String bytes(double d) {
		String unite = "";

		if (d<1024){
			unite="o";
		}
		if (d>=1024){
			d = (double) d/1024L;
			unite="ko";
		}
		if (d>=1024){
			d = (double) d/1024L;
			unite="mo";
		}
		if (d>=1024){
			d = (double) d/1024L;
			unite="go";
		}
		NumberFormat nf = new DecimalFormat(".##");

		if(d==0)
			return "0.0"+unite;
		else
			return ""+nf.format(d)+unite;
	}

	public static byte[] intToByteArray(int value) {
		byte[] b = new byte[4];
		for (int i = 0; i < 4; i++) {
			int offset = (b.length - 1 - i) * 8;
			b[i] = (byte) ((value >>> offset) & 0xFF);
		}
		return b;
	}

	public static int byteArrayToInt(byte[] b) {
		if (b.length == 4) {
			return b[0] << 24 | (b[1] & 0xff) << 16 | (b[2] & 0xff) << 8
			| (b[3] & 0xff);
		} else if (b.length == 2) {
			return 0x00 << 24 | 0x00 << 16 | (b[0] & 0xff) << 8 | (b[1] & 0xff);
		}

		return 0;
	}

	public static String bytesToString(byte[] bytes){
		String chaine="";
		for (int i=0;i<bytes.length;i++){
			chaine+=(char)bytes[i];
		}

		return chaine;
	}

	public static String byteArray2Hex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		return formatter.toString();
	}

}